<template>
  <div>
    <van-uploader
      v-model="fileList"
      multiple="true"
      :after-read="afterRead"
      preview-size="130px"
    />
    <van-button class="button" type="primary" @click="StartUpload">
      点我上传图片
    </van-button>
  </div>
</template>

<script setup>
import { ref } from 'vue'
import axios from 'axios'

const fileList = ref([])
const uploadFormData = ref(null)

const afterRead = (file) => {
  // 创建 FormData 对象并添加文件
  uploadFormData.value = new FormData()
  uploadFormData.value.append('file', file.file)
}

const StartUpload = (file) => {
  if (uploadFormData.value) {
    axios
      .post('http://localhost:3000/api/upload', uploadFormData.value, {
        headers: {
          'Content-Type': 'multipart/form-data'
        }
      })
      .then((response) => {
        if (response.data.success) {
          fileList.value = []
          alert('上传成功')
          fileList.value.push({ url: response.data.url, name: file.name })
        }
      })
      .catch((error) => {
        console.error('上传出错:', error)
      })
  } else {
    alert('没有文件要上传')
  }
}
</script>

<style scoped>
/* 您可以在这里添加一些样式 */
.button {
  margin-bottom: 100px;
}
</style>
